/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:assign-tracer
 * Create Time: 2016年2月1日 上午10:56:08
 */
package com.lenovo.lmrp.server.assigntracer.spi;

import java.util.Objects;

import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.matcher.Matchers;
import com.lenovo.lmrp.api.assigntrace.ITraceTicket;
import com.lenovo.lmrp.base.GuiceRestServer;
import com.lenovo.sdc.framework.mq.AMQClient;
import com.lenovo.sdc.framework.util.AttributeBean;

/**
 * 
 * @author songyz
 * @version v1.0
 */
public class AssignTracerRestServer {
    private static final String PARAM_SERVER_HOST = "assigntracer.host";
    private static final String PARAM_SERVER_PORT = "assigntracer.port";
    private static final String PARAM_SERVER_SSL = "assigntracer.ssl";
    private static final String PARAM_REST_CONTEXT = "assigntracer.context";
    private static final String PARAM_SCAN_PATH = "assigntracer.scanpath";

    private GuiceRestServer restServer;
    private AttributeBean params;
    private AMQClient mqclient;
    
    @Inject
    private Injector parentInjector;

    @Inject
    public AssignTracerRestServer(AttributeBean params) {
        this.params = params;
        restServer = new GuiceRestServer(params.getAttribute(PARAM_SERVER_HOST, "0.0.0.0"),
            params.getAttribute(PARAM_SERVER_PORT, 7003), params.getAttribute(PARAM_SERVER_SSL, false));
    }

    @Inject
    public void set(AMQClient mqclient) {
        this.mqclient = mqclient;
    }
    
    public void start() {
        // start REST API server, listening special port to receive income request
        restServer.start();

        String[] scanpaths = new String[] { params.getAttribute(PARAM_SCAN_PATH,
            "com.lenovo.lmrp.server.assigntracer.spi"), "com.lenovo.sdc.framework.rest" };

        // bind rest api class to child injector, aop module used for trace ticket action
        Module aopModule = new Module() {
            @Override
            public void configure(Binder binder) {
                binder.bindInterceptor(Matchers.subclassesOf(ITraceTicket.class), Matchers.any(), new TicketAOP(mqclient));
            }
        };
        
        Injector child = null;
        if (Objects.isNull(parentInjector)) {
            parentInjector = Guice.createInjector(restServer.bind(scanpaths), aopModule);
            child = parentInjector;
        }
        else
            child = parentInjector.createChildInjector(restServer.bind(scanpaths), aopModule);

        // deploy REST service under GUICE env. to process request
        restServer.deploy(params.getAttribute(PARAM_REST_CONTEXT, ""), child.getBindings().values());
    }

    public void stop() {
        restServer.stop();
    }
}
